<script lang="ts" setup>
import { ref, reactive, watch } from "vue";
import { CirclePlus, RefreshRight, Search, Refresh } from "@element-plus/icons-vue";
// import { CirclePlus, RefreshRight, UploadFilled } from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination";
import { formatDateTime } from "@/utils";

import { ElMessage, type FormInstance, type FormRules } from "element-plus";
// import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from "element-plus"
// const fileList = ref<any>([])
import { checkSign } from "@/utils/validate";
import { addMsgSign, seeMsgSign, seeInterFaceSet } from "@/api/msg";

defineOptions({
  name: "MsgSign"
});
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination();
const loading = ref<boolean>(false);
//#region 增
const dialogVisible = ref<boolean>(false);
const formData = reactive<any>({
  sign: "",
  remark: ""
});
const formRules: FormRules = reactive({
  sign: [{ required: true, validator: checkSign, trigger: "blur" }],
  contentExample: [{ required: true, trigger: "blur", message: "请填写短信内容示例" }],
  userId: [{ required: true, trigger: "blur", message: "请选择助通账号" }]
});
const interFaceData = ref<any>([]);
const getTableData1 = () => {
  loading.value = true;
  seeInterFaceSet({
    page: 1,
    size: 100
  })
    .then((res: any) => {
      interFaceData.value = res.data.list;
    })
    .catch(() => {
      interFaceData.value = [];
    });
};
getTableData1();
const formatterName = (row: any, column: any, celValue: any) => {
  interFaceData.value.filter((item: any) => {
    if (item.id == row.userId) {
      celValue = item.name;
    }
  });
  return celValue;
};
/** 图片改变 */
// const handleChageImg = (file: any, resfileList: any) => {
//   console.log("change")

//   const size = ref(2)
//   const fileSizeFlag = file.size / 1024 / 1024 < size.value
//   if (!fileSizeFlag) {
//     ElMessage.error(`请上传不大于${size.value}M的图片!`)
//     fileList.value = []
//   } else {
//     fileList.value = resfileList
//   }
// }

// 移除图片
// const handleRemove = (file: any) => {
//   const list = fileList.value
//   for (const i in list) {
//     if (list[i].uid === file.uid) {
//       list.splice(i, 1)
//     }
//   }
//   fileList.value = list
// }

const handleCreate = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (currentUpdateId.value === undefined) {
        addMsgSign(formData).then((res: any) => {
          if (res.code === 200) {
            ElMessage.success("新增成功")
            dialogVisible.value = false
            getTableData()
          } else {
            ElMessage.error(res.data)
          }
        })
      }
      // else {
      // getconfigurationRuleApiUpdate(
      //   {
      //     package_id: formData.package_id,
      //     cash_own: formData.cash_own,
      //     cash_super: formData.cash_super,
      //     cash_upup: formData.cash_upup,
      //     cash_money: formData.cash_money
      //   },
      //   false
      // ).then(() => {
      //   ElMessage.success("修改成功")
      //   console.log("修改")
      //   dialogVisible.value = false
      //   getTableData()
      // })
      // }
    } else {
      return false;
    }
  });
};
//#endregion

//#region 删
// const handleDelete = (row: any) => {
//   ElMessageBox.confirm(`确认删除此套餐配置规则？`, "提示", {
//     confirmButtonText: "确定",
//     cancelButtonText: "取消",
//     type: "warning"
//   }).then(() => {
//     console.log(row.package_id)
//     getconfigurationRuleApiDel(row.package_id, false).then(() => {
//       // ElMessage.success("删除成功")
//       getTableData()
//     })
//   })
// }
//#endregion

//#region 改
const currentUpdateId = ref<undefined | string>(undefined);
// const handleUpdate = (row: any) => {
//   console.log(row)
//   dialogVisible.value = true
//   currentUpdateId.value = row.package_id
//   formData.package_id = row.package_id
//   formData.cash_own = row.cash_own
//   formData.cash_super = row.cash_super
//   formData.cash_upup = row.cash_upup
//   formData.cash_money = row.cash_money
// }
//#endregion

// #region 搜索
const searchFormRef = ref<FormInstance | null>(null);
const searchData = reactive({
  sign: ""
});
// 查询按键
const handleSearch = () => {
  if (paginationData.currentPage === 1) {
    getTableData();
  }
  paginationData.currentPage = 1;
};

// 重置按键
const resetSearch = () => {
  searchFormRef.value?.resetFields();
  if (paginationData.currentPage === 1) {
    getTableData();
  }
  paginationData.currentPage = 1;
};

//#region 查
const tableData = ref<any>([]);
const getTableData = () => {
  loading.value = true;
  seeMsgSign({
    page: paginationData.currentPage,
    size: paginationData.pageSize,
    sign: searchData.sign
    // package_id: searchData.package_id
  })
    .then((res: any) => {
      paginationData.total = res.data.total;
      tableData.value = res.data.list;
      console.log(res, "查询的数据");
    })
    .catch(() => {
      tableData.value = [];
    })
    .finally(() => {
      loading.value = false;
    });
};

// 刷新数据
const handleRefresh = () => {
  getTableData();
};
/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true });
//#endregion

// #region 清除验证  清除规则报错信息
const formRef = ref<FormInstance | null>(null);
const clearValidateA = () => {
  formRef.value?.clearValidate();
  formRef.value?.resetFields();
};
const resetForm = () => {
  currentUpdateId.value = undefined;
  clearValidateA();
  // 清空reactive对象里面的key值
  Object.keys(formData).map((key) => {
    delete formData[key];
  });
};
</script>

<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="sign" label="签名">
          <el-input v-model.trim="searchData.sign" placeholder="请输入" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <el-button type="primary" :icon="CirclePlus" @click="dialogVisible = true">添加签名</el-button>
        </div>
        <div>
          <el-tooltip content="刷新表格">
            <el-button type="primary" :icon="RefreshRight" circle @click="handleRefresh" />
          </el-tooltip>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table :data="tableData">
          <el-table-column prop="sign" label="签名" align="center" />
          <el-table-column prop="name" label="接口名称" align="center" :formatter="formatterName" />
          <el-table-column prop="createTime" label="申请时间" align="center">
            <template #default="scope">
              {{ formatDateTime(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="审核状态" align="center">
            <template #default="scope">
              <span v-if="scope.row.auditResult == 1">待审核</span>
              <span v-if="scope.row.auditResult == 2">审核通过</span>
              <span v-if="scope.row.auditResult == 3"
                >审核不通过<span v-if="scope.row.auditMsg" style="color: red">({{ scope.row.auditMsg }})</span></span
              >
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" align="center" />
          <!-- <el-table-column fixed="right" label="操作" width="150" align="center">
            <template #default="scope">
              <el-button type="primary" text bg size="small" @click="handleUpdate(scope.row)">修改</el-button>
              <el-button type="danger" text bg size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column> -->
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 新增 修改 -->
    <el-dialog class="inputdialog" v-model="dialogVisible" title="新增" @close="resetForm" width="60%">
      <div class="Signature-matter">
        <p style="font-weight: bolder">签名规范：</p>
        <p>
          • 签名内容：公司名称或产品名称，字数要求在<span style="color: rgb(255, 0, 0)">2-20个字符</span
          >，不能使用空格和特殊符号“ - + = * &amp; % # @ ~等;
        </p>
        <p>• 签名审核：签名由客服人工审核，审核通过后可使用;</p>
        <p>• 签名规范：须在签名内容前后添加【】。</p>
      </div>
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" label-position="left">
        <el-form-item prop="sign" label="签名内容">
          <el-input v-model="formData.sign" placeholder="签名限制20个字" maxlength="20" show-word-limit />
        </el-form-item>
        <!-- <el-form-item prop="sign_type" label="签名类型">
          <el-radio-group v-model="formData.sign_type" class="ml-4">
            <el-radio label="1" size="large">工信部备案的网站名全称或简称：提供域名备案服务商的后台备案截图</el-radio>
            <el-radio label="2" size="large"
              >公众号或小程序名全称或简称：须提供公众号（小程序）微信开放平台截图</el-radio
            >
            <el-radio label="3" size="large"
              >APP名全称或简称：须提供任一应用商店的下载链接与该应用商店的后台管理截图</el-radio
            >
          </el-radio-group>
        </el-form-item> -->
        <!-- <el-form-item prop="sign_image" label="上传图片">
          <el-upload
            v-model:file-list="fileList"
            class="upload-demo"
            :auto-upload="false"
            accept="image/*"
            multiple
            :on-change="handleChageImg"
            :on-remove="handleRemove"
            :limit="1"
          >
            <el-button type="primary" :icon="UploadFilled">文件上传</el-button>
            <template #tip>
              <div class="el-upload__tip">格式要求:支持jpg,jpeg,gif,pag等格式照片,大小不超过2M</div>
            </template>
          </el-upload>
        </el-form-item> -->
        <el-form-item prop="contentExample" label="内容示例">
          <el-input
            v-model="formData.contentExample"
            placeholder="例如【中国移动】您的验证码是:12345。"
            maxlength="500"
            show-word-limit
            type="textarea"
          />
        </el-form-item>
        <el-form-item prop="remark" label="备注内容">
          <el-input
            v-model="formData.remark"
            placeholder="请输入备注内容50字以内"
            maxlength="50"
            show-word-limit
            type="textarea"
          />
        </el-form-item>
        <el-form-item prop="userId" label="助通账号">
          <!-- <el-input v-model="formData.userId" placeholder="签名限制20个字" maxlength="20" show-word-limit /> -->
          <el-select v-model="formData.userId" clearable filterable placeholder="请选择助通账号" style="width: 240px">
            <el-option v-for="item in interFaceData" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate">提交审核</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;

  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}

.Signature-matter {
  margin-bottom: 20px;
  border: 1px solid #6cf;
  background: #e5f0ff;
  padding: 10px 14px;
  border-radius: 5px;
  font-size: 12px;
}

:deep(.el-radio-group) {
  display: block;
}

:deep(.el-radio.el-radio--large) {
  display: block !important;
}
</style>
